const { postRequest } = require('./request')
const api = require('./api')
const { updateUserInfo } = require('../utils/user')
const { showModal, log } = require('../utils/common')
//获取网络请求使用的code
function wxLogin() {
  //重新登录
  wx.login({
    success: res => {
      if (res.code) {
        updateUserInfo({ code: res.code });
      } else {
        showModal(
          {
            content: '登录失败！' + res.errMsg,
            showCancel: true,
          },
          wxLogin
        );
      }
    }
  });
}

//记录微信的code并返回openid
function fetchRecordRequest(code) {
  return postRequest(api.loginRecord, { code }).then(res => {
    const userObj = {
      code,
      openId: res.data,
      role: -1, // 授权用户为 0
    };
    updateUserInfo(userObj);
  }).catch(err => {
    log(err);
  });
}

function doLogin(params) {
  return postRequest(api.login, params)
}

function getVerficationCode(params) {
  return postRequest(api.loginVerfication, params)
}

function decryptMobile(params) {
  return postRequest(api.decryptMobile, params)
}

module.exports = {
  wxLogin,
  fetchRecordRequest,
  doLogin,
  getVerficationCode,
  decryptMobile
}